package cn.edu.dgut.utils;

import cn.edu.dgut.infomation.LocalUserInfo;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import java.io.*;

public class ReadFile {
    private long max_user_number = 20190001;
    private String fileName = "userInfo.txt";

    static {
        File f = new File("userInfo.txt");
        if (!f.exists()){
            try {
                f.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * getCount()
     * @return 返回用户数
     * @throws IOException
     */
    public int getCount() throws IOException {
        int n = 0;
        Reader reader = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String str= null;
        while ((str = bufferedReader.readLine()) != null) {
            //过滤掉空格行
            if(!str.trim().equals("")){
                n++;
            }
        }
        // 注意这两个关闭的顺序
        bufferedReader.close();
        reader.close();
        return n;
    }

    /**
     * getUers()
     * @return 返回用户数组
     * @throws IOException
     */
    public LocalUserInfo[] getUers() throws IOException {
        int n=getCount();
        int len = 0;
        LocalUserInfo[] users;
        if(n==0){
            return null;
        }
        users = new LocalUserInfo[n];
        Jsonb jsonb = JsonbBuilder.create();

        Reader reader = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(reader);
        String str= null;
        while ((str = bufferedReader.readLine()) != null) {
            //过滤掉空格行
            if(!str.trim().equals("")){
                users[len++] = jsonb.fromJson(str,LocalUserInfo.class);
            }
        }
        // 注意这两个关闭的顺序
        bufferedReader.close();
        reader.close();
        return users;
    }

    /**
     * find(String str)
     * 根据 工号/手机号/邮箱 来查找用户信息
     * @param str  工号/手机号/邮箱
     * @return 返回符合条件的用户
     * @throws IOException
     */
    public  LocalUserInfo find(String str) throws IOException {
        LocalUserInfo[] users = getUers();
        if(users!=null){
            for (int i = 0; i < users.length; i++) {
                if(users[i].getUser_number().equals(str)){
                    return users[i];
                }
                if(users[i].getEmail()!=null){
                    if(users[i].getEmail().equals(str))
                        return users[i];
                }
                if(users[i].getPhone_number()!=null){
                    if(users[i].getPhone_number().equals(str))
                        return users[i];
                }
            }
        }
        return null;
    }

    /**
     * getMaxNumber()
     * @return 返回最大的工号
     * 注册时的工号以 最大的工号+1 得到
     */
    public String getMaxNumber() throws IOException {
        LocalUserInfo[] users = getUers();
        /*for(int i=0;i<users.length;i++){
            if(Integer.valueOf(users[i].getUser_number())>max_user_number)
                max_user_number = Integer.valueOf(users[i].getUser_number());
        }*/
        if(users!=null)
            max_user_number = max_user_number + users.length;//工号是以20190000为基值生成
        return String.valueOf(max_user_number);
    }

    /**
     * 在userInfo.txt中追加注册信息
     */
    public void setUserInfo(String userinfo){
        BufferedWriter out = null;
        File file = new File("userInfo.txt");
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true)));
            out.write(userinfo+"\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void resetUserInfo(LocalUserInfo user) throws IOException {
        LocalUserInfo[] users = getUers();
        StringBuffer bu = new StringBuffer();
        BufferedWriter out = null;
        Jsonb jsonb = JsonbBuilder.create();
        File file = new File("userInfo.txt");
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file,false)));
        for (int i = 0; i < users.length; i++) {
            if(user.getUser_number().equals(users[i].getUser_number())){       //替换用户信息（根据工号判断）
                users[i] = user;
            }
            String infoJson = jsonb.toJson(users[i]);
            bu.append(infoJson+"\n");
        }
        String userString = bu.toString();
        out.write(userString);
        out.close();
    }
}
